
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Tathata.Common.BLL.Entities;
using Tathata.Common.BLL.Managers;
using Tathata.Common.Utils;
using Tathata.Common.BLL.EntityCollections;
using System.Collections.Generic;
using Tathata.Web.Administration.Modules;

namespace Tathata.Web.Administration
{
    public partial class Administration_CategoryDetails : BaseNopAdministrationPage
    {
        private void BindData()
        {
            Category category = CategoryManager.GetByCategoryID(this.CategoryID);

            if (category != null)
            {
                this.txtName.Text = category.Name;
                this.txtDescription.Value = category.Description;
                CommonHelper.SelectListItem(this.ddlTemplate, category.TemplateID);
                this.txtMetaKeywords.Text = category.MetaKeywords;
                this.txtMetaDescription.Text = category.MetaDescription;
                this.txtMetaTitle.Text = category.MetaTitle;
                this.txtSEName.Text = category.SEName;
                ParentCategory.SelectedCategoryId = category.ParentCategoryID;

                Picture categoryPicture = category.Picture;
                btnRemoveCategoryImage.Visible = categoryPicture != null;
                string pictureUrl = PictureManager.GetPictureUrl(categoryPicture, 100, 80);
                this.iCategoryPicture.ImageUrl = pictureUrl;

                this.cbPublished.Checked = category.Published;
                this.txtDisplayOrder.Value = category.DisplayOrder;
                this.ParentCategory.BindData();
                
                ProductCategoryCollection existingProductCategoryCollection = category.ProductCategories;
                List<ProductCategoryMappingHelperClass> productCategoryMappings = GetProductCategoryMappings(existingProductCategoryCollection);
                gvProductMappings.DataSource = productCategoryMappings;
                gvProductMappings.DataBind();
            }
            else
                Response.Redirect("Categories.aspx");
        }

        private void FillDropDowns()
        {
            this.ddlTemplate.Items.Clear();
            CategoryTemplateCollection categoryTemplates = CategoryTemplateManager.GetAllCategoryTemplates();
            foreach (CategoryTemplate categoryTemplate in categoryTemplates)
            {
                ListItem item2 = new ListItem(categoryTemplate.Name, categoryTemplate.CategoryTemplateID.ToString());
                this.ddlTemplate.Items.Add(item2);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.FillDropDowns();
                this.BindData();
            }
        }

        protected void SaveButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                try
                {
                    Category category = CategoryManager.GetByCategoryID(this.CategoryID);

                    if (category != null)
                    {
                        Picture categoryPicture = category.Picture;
                        HttpPostedFile categoryPictureFile = fuCategoryPicture.PostedFile;
                        if ((categoryPictureFile != null) && (!String.IsNullOrEmpty(categoryPictureFile.FileName)))
                        {
                            byte[] categoryPictureBinary = PictureManager.GetPictureBits(categoryPictureFile.InputStream, categoryPictureFile.ContentLength);
                            if (categoryPicture != null)
                                categoryPicture = PictureManager.UpdatePicture(categoryPicture.PictureID, categoryPictureBinary, categoryPictureFile.ContentType, true);
                            else
                                categoryPicture = PictureManager.InsertPicture(categoryPictureBinary, categoryPictureFile.ContentType, true);
                        }
                        int categoryPictureID = 0;
                        if (categoryPicture != null)
                            categoryPictureID = categoryPicture.PictureID;

                        category = CategoryManager.UpdateCategory(category.CategoryID, txtName.Text, txtDescription.Value, int.Parse(this.ddlTemplate.SelectedItem.Value),
                             txtMetaKeywords.Text, txtMetaDescription.Text, txtMetaTitle.Text, txtSEName.Text, ParentCategory.SelectedCategoryId,
                            categoryPictureID, cbPublished.Checked, category.Deleted, txtDisplayOrder.Value, category.CreatedOn, DateTime.Now);

                        foreach (GridViewRow row in gvProductMappings.Rows)
                        {
                            CheckBox cbProductInfo = row.FindControl("cbProductInfo") as CheckBox;
                            HiddenField hfProductID = row.FindControl("hfProductID") as HiddenField;
                            HiddenField hfProductCategoryID = row.FindControl("hfProductCategoryID") as HiddenField;
                            CheckBox cbFeatured = row.FindControl("cbFeatured") as CheckBox;
                            NumericTextBox txtRowDisplayOrder = row.FindControl("txtDisplayOrder") as NumericTextBox;
                            int productCategoryID = int.Parse(hfProductCategoryID.Value);
                            int productID = int.Parse(hfProductID.Value);
                            int displayOrder = txtRowDisplayOrder.Value;

                            if (productCategoryID > 0 && !cbProductInfo.Checked)
                                ProductCategoryManager.DeleteProductCategory(productCategoryID);
                            if (productCategoryID > 0 && cbProductInfo.Checked)
                                ProductCategoryManager.UpdateProductCategory(productCategoryID, productID, category.CategoryID, cbFeatured.Checked, displayOrder);
                            if (productCategoryID == 0 && cbProductInfo.Checked)
                                ProductCategoryManager.InsertProductCategory(productID, category.CategoryID, cbFeatured.Checked, displayOrder);
                        }
                       
                    }
                    Response.Redirect(string.Format("CategoryDetails.aspx?CategoryID={0}", category.CategoryID));
                }
                catch (Exception exc)
                {
                    ProcessException(exc);
                }
            }
        }

        protected void DeleteButton_Click(object sender, EventArgs e)
        {
            try
            {
                CategoryManager.MarkCategoryAsDeleted(this.CategoryID);
                Response.Redirect("Categories.aspx");
            }
            catch (Exception exc)
            {
                ProcessException(exc);
            }
        }

        protected void btnRemoveCategoryImage_Click(object sender, EventArgs e)
        {
            try
            {
                Category category = CategoryManager.GetByCategoryID(this.CategoryID);
                if (category != null)
                {
                    PictureManager.DeletePicture(category.PictureID);
                    CategoryManager.RemoveCategoryPicture(category.CategoryID);
                    BindData();
                }
            }
            catch (Exception exc)
            {
                ProcessException(exc);
            }
        }

        private List<ProductCategoryMappingHelperClass> GetProductCategoryMappings(ProductCategoryCollection ExistingProductCategoryCollection)
        {
            ProductCollection productCollection = ProductManager.GetAllProducts();
            List<ProductCategoryMappingHelperClass> result = new List<ProductCategoryMappingHelperClass>();
            for (int i = 0; i < productCollection.Count; i++)
            {
                Product product = productCollection[i];
                ProductCategory existingProductCategory = ExistingProductCategoryCollection.FindProductCategory(product.ProductID, this.CategoryID);
                ProductCategoryMappingHelperClass pcm = new ProductCategoryMappingHelperClass();
                if (existingProductCategory != null)
                {
                    pcm.ProductCategoryID = existingProductCategory.ProductCategoryID;
                    pcm.IsMapped = true;
                    pcm.IsFeatured = existingProductCategory.IsFeaturedProduct;
                    pcm.DisplayOrder = existingProductCategory.DisplayOrder;
                }
                else
                {
                    pcm.DisplayOrder = 1;
                }
                pcm.ProductID = product.ProductID;
                pcm.ProductInfo = product.Name;

                result.Add(pcm);                
            }

            return result;
        }

        private class ProductCategoryMappingHelperClass
        {
            public int ProductCategoryID { get; set; }
            public int ProductID { get; set; }
            public string ProductInfo { get; set; }
            public bool IsMapped { get; set; }
            public bool IsFeatured { get; set; }
            public int DisplayOrder { get; set; }
        }

        public int CategoryID
        {
            get
            {
                return CommonHelper.QueryStringInt("CategoryID");
            }
        }
    }
}
